#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import subprocess
from typing import List
from ..core.logger import Logger

class Merger:
    def __init__(self):
        self.logger = Logger()
    
    def merge_video_audio(self, video_path: str, audio_path: str, output_path: str) -> None:
        """合并视频和音频
        
        Args:
            video_path: 视频文件路径
            audio_path: 音频文件路径
            output_path: 输出文件路径
        """
        try:
            cmd = [
                'ffmpeg',
                '-i', video_path,
                '-i', audio_path,
                '-c:v', 'copy',
                '-c:a', 'aac',
                '-strict', 'experimental',
                output_path
            ]
            
            subprocess.run(cmd, check=True, capture_output=True)
            self.logger.info(f"视频和音频合并完成: {output_path}")
            
        except subprocess.CalledProcessError as e:
            self.logger.error(f"合并失败: {e.stderr.decode()}")
            raise
    
    def merge_video_parts(self, video_parts: List[str], output_path: str) -> None:
        """合并多个视频片段
        
        Args:
            video_parts: 视频片段路径列表
            output_path: 输出文件路径
        """
        try:
            # 创建临时文件列表
            temp_list = output_path + '.list'
            with open(temp_list, 'w', encoding='utf-8') as f:
                for part in video_parts:
                    f.write(f"file '{part}'\n")
            
            # 使用ffmpeg合并
            cmd = [
                'ffmpeg',
                '-f', 'concat',
                '-safe', '0',
                '-i', temp_list,
                '-c', 'copy',
                output_path
            ]
            
            subprocess.run(cmd, check=True, capture_output=True)
            self.logger.info(f"视频片段合并完成: {output_path}")
            
            # 删除临时文件
            os.remove(temp_list)
            
        except subprocess.CalledProcessError as e:
            self.logger.error(f"合并失败: {e.stderr.decode()}")
            raise
    
    def merge_video_subtitle(self, video_path: str, subtitle_path: str, output_path: str) -> None:
        """将字幕嵌入视频
        
        Args:
            video_path: 视频文件路径
            subtitle_path: 字幕文件路径
            output_path: 输出文件路径
        """
        try:
            cmd = [
                'ffmpeg',
                '-i', video_path,
                '-vf', f"subtitles={subtitle_path}",
                '-c:a', 'copy',
                output_path
            ]
            
            subprocess.run(cmd, check=True, capture_output=True)
            self.logger.info(f"视频和字幕合并完成: {output_path}")
            
        except subprocess.CalledProcessError as e:
            self.logger.error(f"合并失败: {e.stderr.decode()}")
            raise 